import {
	ACCESS_TOKEN
} from '@/store/mutation-types'
import storage from '@/utils/storage'
import * as LoginApi from '@/api/login'
import * as UserApi from '@/api/user'
import { getDict, getPermission } from '@/api/dict.js'
//引入websocket文件
import wsRequest from '@/config/websocket.js'
import Vue from 'vue'

// 登陆成功后执行
const loginSuccess = (commit, {
	token
}) => {
	// 过期时间30天
	const expiryTime = 30 * 86400
	// 保存tokne和userId到缓存
	storage.set(ACCESS_TOKEN, token, expiryTime)
	// 记录到store全局变量
	commit('SET_TOKEN', token)
}

export const state = {
	// 用户认证token
	token: '',
	// 用户信息
	userInfo: null,
	// 权限代码
	authorities: null,
	// 字典信息
	dictInfo: null,
	sewingName: '',
}

export const mutations = {
	SET_TOKEN: (state, value) => {
		state.token = value
	},
	SET_SEWING:(state, value) => {
		state.sewingName = value
	},
	SET_USER: (state, value) => {
		state.userInfo = value
	},
	SET_AUTH: (state, value) => {
		state.authorities = value
	},
	SET_DICT: (state, value) => {
		state.dictInfo = value
	},
}

export const actions = {

	// 用户登录(普通登录: 输入账号、密码和验证码)
	Login({
		commit
	}, data) {
		return new Promise((resolve, reject) => {
			LoginApi.login(data).then(response => {
				const result = response;
				// console.log("🚀 ~ file: user.js:63 ~ LoginApi.login ~ result:", result)
				loginSuccess(commit, {
					token: result.data.token
				})
				resolve(response)
			}).catch(reject)
		})
	},

	// 用户信息
	Info({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			// if (state.userInfo) {
			// 	return resolve(state.userInfo)
			// }
			UserApi.getInfo().then(response => {
				const result = response;
				commit('SET_USER', result.data)
				storage.set('userInfo', result.data)
				// commit('SET_AUTH', result.authorities)
				// storage.set('principal', result.principal)
				// storage.set('authorities', result.authorities)
				resolve(response)
			}).catch(reject)
			// 获取字典信息
			// getDict().then(res => {
			// 	commit('SET_DICT', res.data)
			// 	resolve(res)
			// }).catch(reject)
			getPermission().then(res => {
				storage.set('authorities', res.data)
				resolve(res)
			}).catch(reject)
		})
	},

	// 退出登录
	Logout({
		commit
	}, data) {
		commit('SET_SEWING', '')
		commit('SET_TOKEN', '')
		commit('SET_AUTH', '')
		storage.remove('AccessToken')
		storage.remove('authorities')
		storage.remove('currentSewLineInfo')
		storage.remove('principal')
	}

}
